package com.zhijian.medical.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhijian.medical.entity.dto.PersonDto;
import com.zhijian.medical.entity.po.RoutineSingleSample;
import com.zhijian.medical.entity.po.RoutineSingleSampleQp;
import com.zhijian.medical.entity.vo.request.*;
import com.zhijian.medical.entity.vo.response.RoutinePathologyBmInfoVo;
import com.zhijian.medical.entity.vo.response.RoutinePathologyQpVo;
import com.zhijian.medical.entity.vo.response.RoutineSingleSampleVo;
import com.zhijian.medical.holder.CurrentUserHolder;
import com.zhijian.medical.service.CacheService;
import com.zhijian.medical.service.RoutinePathologyQpService;
import com.zhijian.medical.service.RoutineSingleSampleQpService;
import com.zhijian.medical.service.RoutineSingleSampleService;
import com.zhijian.response.annotation.Response;
import com.zhijian.util.page.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 常规病例切片 控制层
 *
 * @author auto
 * @version 1.0
 * @date 2024-06-23 15:24:06
 */
@Slf4j
@Controller
@Api(tags = "常规病理-切片")
public class RoutinePathologyQpController {

    @Autowired
    private RoutinePathologyQpService service;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private RoutineSingleSampleService singleSampleService;

    @Autowired
    private RoutineSingleSampleQpService routineSingleSampleQpService;

    /**
     * 样本详情
     * type 切片类型
     * handle 操作类型
     * @return
     */
    @Response
    @GetMapping("/routine/pathology/qp/sample")
    @ApiOperation("样本详情")
    public List<RoutineSingleSampleQp> pathologySampleInfo(Integer type, Integer handle) {
        log.info("{} | yangben query", this.getClass().getSimpleName());
        String s = readSampleNum(CurrentUserHolder.getUser(), type);
        if (StringUtils.isBlank(s)) {
            return new ArrayList<>();
        }
        List<String> split = Arrays.asList(s.split(","));
        return singleSampleService.selectQpList(RoutineSingleSampleSearchVo.builder()
                .numberList(split)
                .patientType(handle)
                .build());
    }

    /**
     * 根据type获取不同的切片数据
     * @param personDto 当前登陆人
     * @param type 切片类型
     * @return
     */
    private String readSampleNum(PersonDto personDto, Integer type){
        String sampleNum;
        if(type != null && type <= 0){
            sampleNum = cacheService.get("gl_qiepian:" + personDto.getId());
        }else {
            sampleNum = cacheService.get("gl_qiepian:"+type+":" + personDto.getId());
        }
        return sampleNum;
    }

    /**
     * 获取切片详情
     * @return
     */
    @Response
    @GetMapping("/routine/pathology/qp/info/{numbs}")
    @ApiOperation("获取切片详情/蜡块号输入")
    public RoutinePathologyBmInfoVo pathologyQpInfo(@ApiParam(name = "numbs", value = "蜡块号")
                                                        @PathVariable("numbs") String numbs, Integer type) {
        log.info("{} | query info", this.getClass().getSimpleName());
        return service.pathologyInfo(numbs, type);
    }

    /**
     * 白片设置切片数量
     * @return
     */
    @Response
    @GetMapping("/routine/pathology/qp/num")
    @ApiOperation("白片设置切片数量")
    public void pathologyQpNum(Integer num) {
        log.info("{} | query info", this.getClass().getSimpleName());
        cacheService.set("gl_qiepian_num:" + CurrentUserHolder.getUser().getId(), num.toString());
    }

    /**
     * 结束切片
     * @return
     */
    @Response
    @GetMapping("/routine/pathology/qp/end")
    @ApiOperation("结束切片")
    public boolean pathologyInfo(Integer type) {
        log.info("{} | end qiepian", this.getClass().getSimpleName());
        PersonDto personDto = CurrentUserHolder.getUser();
        RoutineSingleSampleQpService.QpTypeEnum[] qpTypeEnums = RoutineSingleSampleQpService.QpTypeEnum.values();
        //清除设置的切片数量
        cacheService.del("gl_qiepian_num:" + CurrentUserHolder.getUser().getId());
        if (type != null && type > 0){
            RoutineSingleSampleQpService.QpTypeEnum qpTypeEnum = qpTypeEnums[type];
            routineSingleSampleQpService.endQp(personDto, qpTypeEnum);
            cacheService.del("gl_qiepian:"+ type +":" + CurrentUserHolder.getUser().getId());
        }else {
            routineSingleSampleQpService.endQp(personDto, RoutineSingleSampleQpService.QpTypeEnum.HE);
            cacheService.del("gl_qiepian:" + CurrentUserHolder.getUser().getId());
        }
        return true;
    }

    /**
     * 批量修改染色架编号
     * @return
     */
    @Response
    @PostMapping("/routine/pathology/qp/code")
    @ApiOperation("批量修改染色架编号")
    public boolean changeCode(@RequestBody(required = false) List<RoutineSingleSampleSaveOrUpdateQpVo> samples) {
        if (samples == null){
            return false;
        }
        List<Long> idList = samples.stream().map(RoutineSingleSampleSaveOrUpdateQpVo::getId).collect(Collectors.toList());
        Map<Long, RoutineSingleSampleQp> oldMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(idList)){
            QueryWrapper<RoutineSingleSampleQp> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("id", idList);
            List<RoutineSingleSampleQp> oldList = routineSingleSampleQpService.list(queryWrapper);
            oldMap = oldList.stream().collect(Collectors.toMap(RoutineSingleSampleQp::getId, e -> e));
        }
        log.info("{} | changeCode qiepian ", this.getClass().getSimpleName());
        for (RoutineSingleSampleSaveOrUpdateQpVo sample : samples) {
            RoutineSingleSampleQp upd = new RoutineSingleSampleQp();
            upd.setId(sample.getId());
            upd.setRsjCode(sample.getRsjCode());
            routineSingleSampleQpService.updateById(upd);
            RoutineSingleSampleQp old = oldMap.get(sample.getId());
            if (old != null){
                singleSampleService.updateByPrimaryKeySelective(RoutineSingleSample.builder()
                        .id(old.getSampleId())
                        .rsjCode(sample.getRsjCode())
                        .build());
            }
        }
        return true;
    }

    private boolean oldUpdateRsj(@RequestBody(required = false) List<RoutineSingleSampleSaveOrUpdateQpVo> samples){
        for (RoutineSingleSampleSaveOrUpdateQpVo sample : samples) {
            boolean flag = singleSampleService.updateByPrimaryKeySelective(RoutineSingleSample.builder()
                    .id(sample.getId())
                    .rsjCode(sample.getRsjCode())
                    .build());
            if (!flag) {
                return false;
            }
        }
        return true;
    }
}